"""
自然语言服务协调器
分析用户查询并选择最合适的服务进行调用
"""

import json
import re
import hashlib
import asyncio
import inspect
from typing import Dict, Any, Optional, List, Tuple
from datetime import datetime, timedelta

# 导入日志模块
from src.utils.logging import get_logger

# 导入ServiceStatus枚举
from src.services.service_registry import ServiceStatus

# 导入异步工具
from src.utils.async_utils import resolve_awaitable, run_in_async_context, AsyncHelper

# 初始化日志记录器
logger = get_logger(__name__)

# 延迟导入以避免依赖问题
def get_llm():
    try:
        from src.research_core.model import get_llm as _get_llm
        return _get_llm()
    except ImportError:
        return None

def get_service_registry():
    try:
        from src.containers import get_service_registry as _get_service_registry
        return _get_service_registry()
    except ImportError:
        from src.services.service_registry import service_registry
        return service_registry

def create_prompt_messages(system_content: str, human_content: str) -> List[Dict[str, str]]:
    """创建提示消息"""
    return [
        {"role": "system", "content": system_content},
        {"role": "user", "content": human_content}
    ]


class ServiceOrchestrator:
    """服务协调器，分析用户查询并选择服务"""
    
    def __init__(self, llm=None):
        self.llm = llm or get_llm()
        self.service_registry = get_service_registry()
        self.query_cache: Dict[str, Tuple[Dict[str, Any], datetime]] = {}
        self.cache_ttl = timedelta(minutes=5)  # 缓存5分钟
        self.batch_queue = asyncio.Queue()
        self.batch_processing_task = None
        self.batch_size = 10
        self.batch_timeout = 0.1  # 100ms
        self.service_weights = {
            "research_assistant": 1.0,
            "user_management": 0.9,
            "ticket_system": 0.8,
            "knowledge_graph": 0.7,
            "group_management": 0.6
        }
        self.cache_stats = {"hits": 0, "misses": 0, "semantic_matches": 0}  # 缓存统计
        self._semaphore = asyncio.Semaphore(20)  # 限制并发分析数量
        self.logger = logger
    
    async def analyze_query(self, user_query: str) -> Dict[str, Any]:
        """分析用户查询并选择服务"""
        async with self._semaphore:  # 限制并发
            # 检查缓存，传递原始查询文本以支持语义匹配
            cache_key = self._generate_cache_key(user_query)
            cached_result = self._get_from_cache(cache_key, original_query=user_query)
            if cached_result:
                # 验证缓存结果中的服务是否存在
                selected_service = cached_result.get("selected_service", "")
                if self.service_registry.service_exists(selected_service):
                    # 验证缓存结果中的参数
                    validated_params = self._validate_parameters(selected_service, cached_result.get("parameters", {}))
                    if validated_params:
                        cached_result["parameters"] = validated_params
                    self.cache_stats["hits"] += 1
                    return cached_result
                else:
                    # 缓存的服务不存在，清除缓存并继续处理
                    if cache_key in self.query_cache:
                        del self.query_cache[cache_key]
                    self.cache_stats["misses"] += 1
            else:
                self.cache_stats["misses"] += 1
            
            available_services = self.service_registry.get_all_services()
            
            # 首先尝试基于关键词的快速匹配
            fast_result = self._fast_service_selection(user_query)
            if fast_result and fast_result.get("confidence", 0) > 0.8:
                # 验证快速匹配结果中的参数
                selected_service = fast_result.get("selected_service", "")
                if selected_service:
                    validated_params = self._validate_parameters(selected_service, fast_result.get("parameters", {}))
                    if validated_params:
                        fast_result["parameters"] = validated_params
                    
                    # 检查服务依赖
                    dependencies_status = self._check_service_dependencies(selected_service)
                    if not dependencies_status["all_available"]:
                        fast_result["warnings"] = [f"依赖服务不可用: {', '.join(dependencies_status['missing_dependencies'])}"]
                
                self._add_to_cache(cache_key, fast_result, original_query=user_query)
                return fast_result
            
            # 构建提示词
            prompt = self._build_service_selection_prompt(user_query, available_services)
            
            try:
                if self.llm is None:
                    # 如果LLM不可用，使用备选方案
                    result = self._fallback_service_selection(user_query)
                    # 验证备选方案结果中的参数
                    selected_service = result.get("selected_service", "")
                    if selected_service:
                        validated_params = self._validate_parameters(selected_service, result.get("parameters", {}))
                        if validated_params:
                            result["parameters"] = validated_params
                
                # 使用LLM分析查询，移除超时限制
                response = await self.llm.ainvoke(prompt)
                # 确保传递给_parse_response的是字符串类型
                if hasattr(response, 'content'):
                    response_content = response.content
                else:
                    response_content = str(response)
                
                if not isinstance(response_content, str):
                    response_content = str(response_content)
                    
                result = self._parse_response(response_content, user_query)
                
                # 验证和增强参数
                selected_service = result.get("selected_service", "")
                if selected_service:
                    # 标准化服务名称
                    normalized_service_name = self._normalize_service_name(selected_service)
                    if normalized_service_name != selected_service:
                        result["selected_service"] = normalized_service_name
                        result["original_service_name"] = selected_service
                    
                    # 验证和补全参数
                    parameters = result.get("parameters", {})
                    validated_params = self._validate_parameters(normalized_service_name, parameters)
                    
                    # 获取默认参数并合并
                    default_params = self._get_default_parameters(normalized_service_name)
                    if default_params:
                        for param_name, param_value in default_params.items():
                            if param_name not in validated_params:
                                validated_params[param_name] = param_value
                    
                    result["parameters"] = validated_params
                    
                    # 检查服务依赖
                    dependencies_status = self._check_service_dependencies(normalized_service_name)
                    if not dependencies_status["all_available"]:
                        if "warnings" not in result:
                            result["warnings"] = []
                        result["warnings"].append(f"依赖服务不可用: {', '.join(dependencies_status['missing_dependencies'])}")
                
                self._add_to_cache(cache_key, result, original_query=user_query)
                # 使用async_utils工具解析协程对象
                result = await resolve_awaitable(result)
                return result
            except Exception as e:
                # 如果LLM调用失败，使用基于关键词的备选方案
                self.logger.warning(f"LLM调用失败: {str(e)}，使用备选服务选择方案")
                result = self._fallback_service_selection(user_query)
                
                # 验证备选方案结果中的参数
                selected_service = result.get("selected_service", "")
                if selected_service:
                    validated_params = self._validate_parameters(selected_service, result.get("parameters", {}))
                    if validated_params:
                        result["parameters"] = validated_params
                
                self._add_to_cache(cache_key, result)
                # 使用async_utils工具解析协程对象
                result = await resolve_awaitable(result)
                return result
    
    def _build_service_selection_prompt(self, user_query: str, available_services: Dict[str, Any]) -> List[Dict[str, str]]:
        """构建服务选择提示词"""
        
        services_info = []
        # 按照相关性排序服务
        relevant_services = self.service_registry.find_relevant_services(user_query, top_n=5)
        relevant_service_names = [s['name'] for s in relevant_services]
        
        # 优先列出相关服务
        for service_data in relevant_services:
            name = service_data['name']
            service_desc = f"- {name}: {service_data['description']}"
            if service_data.get('parameters'):
                params_desc = ", ".join([f"{k}: {v}" for k, v in service_data['parameters'].items()])
                service_desc += f" (参数: {params_desc})"
            if service_data.get('examples'):
                examples = service_data['examples'][:2]  # 只显示前2个示例
                service_desc += f" (示例: {', '.join(examples)})"
            services_info.append(service_desc)
        
        # 添加其他服务
        for name, info in available_services.items():
            if name not in relevant_service_names:
                service_desc = f"- {name}: {info['description']}"
                if info.get('parameters'):
                    params_desc = ", ".join([f"{k}: {v}" for k, v in info['parameters'].items()])
                    service_desc += f" (参数: {params_desc})"
                if info.get('examples'):
                    examples = info['examples'][:1]  # 只显示1个示例
                    service_desc += f" (示例: {', '.join(examples)})"
                services_info.append(service_desc)
        
        services_text = "\n".join(services_info)
        
        # 明确列出所有可用服务名称
        all_service_names = list(available_services.keys())
        service_names_text = ", ".join(all_service_names)
        
        system_content = f"""你是一个智能服务协调员。根据用户查询分析需要调用哪个服务，并提取相关参数。

请严格遵循以下规则：
1. 仔细分析用户查询的意图
2. 选择最匹配的服务名称，必须从以下列表中选择: {service_names_text}
3. 从查询中提取必要的参数值
4. 如果查询不明确，选择最可能的相关服务
5. 返回格式必须是有效的JSON

可用服务列表："""

        human_content = f"""
用户查询: {user_query}

可用服务:
{services_text}

请返回JSON格式:
{{
    "selected_service": "service_name",
    "confidence": 0.95,
    "parameters": {{
        "param1": "value1",
        "param2": "value2"
    }},
    "reasoning": "选择该服务的理由"
}}
"""
        
        return create_prompt_messages(system_content, human_content)
    
    def _parse_response(self, response_text: str, user_query: str) -> Dict[str, Any]:
        """解析模型响应"""
        try:
            # 尝试提取JSON部分
            json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
            if json_match:
                json_str = json_match.group()
                result = json.loads(json_str)
                
                # 验证服务是否存在，如果不存在则使用备选方案
                selected_service = result.get('selected_service', '')
                if not self.service_registry.service_exists(selected_service):
                    # 记录警告日志
                    import logging
                    logging.warning(f"LLM返回了不存在的服务: {selected_service}，使用备选服务选择方案")
                    
                    # 分析用户查询，尝试直接映射到正确的服务
                    fallback_result = self._fallback_service_selection(user_query)
                    
                    # 如果LLM返回的参数有价值，尝试将其合并到备选方案中
                    if 'parameters' in result and isinstance(result['parameters'], dict):
                        fallback_result.setdefault('parameters', {})
                        # 合并参数，但以备选方案的参数为主
                        for param_name, param_value in result['parameters'].items():
                            if param_name not in fallback_result['parameters']:
                                fallback_result['parameters'][param_name] = param_value
                    
                    return fallback_result
                
                # 确保置信度在合理范围内
                if "confidence" in result:
                    result["confidence"] = max(0.0, min(1.0, result["confidence"]))
                
                return result
            else:
                # 如果没有找到JSON，使用备选方案
                return self._fallback_service_selection(user_query)
        except (json.JSONDecodeError, AttributeError) as e:
            # 记录解析错误
            import logging
            logging.warning(f"解析LLM响应失败: {str(e)}，使用备选服务选择方案")
            return self._fallback_service_selection(user_query)
    
    def _generate_cache_key(self, user_query: str, service_params: Optional[Dict[str, Any]] = None) -> str:
        """
        生成缓存键，支持查询和参数组合
        
        Args:
            user_query: 用户查询文本
            service_params: 可选的服务参数
            
        Returns:
            缓存键字符串
        """
        # 基础缓存键包含查询文本
        base_key = hashlib.md5(user_query.encode()).hexdigest()
        
        # 如果有参数，添加参数信息到缓存键
        if service_params:
            # 排序参数以确保一致性
            sorted_params = sorted(service_params.items())
            params_str = json.dumps(sorted_params, sort_keys=True)
            params_hash = hashlib.md5(params_str.encode()).hexdigest()
            return f"{base_key}:{params_hash}"
        
        return base_key
    
    def _get_from_cache(self, cache_key: str, original_query: Optional[str] = None) -> Optional[Dict[str, Any]]:
        """
        从缓存获取结果，支持精确匹配和语义匹配
        
        Args:
            cache_key: 缓存键
            original_query: 原始查询文本，用于语义匹配
            
        Returns:
            缓存的结果，如果没有找到则返回None
        """
        # 精确匹配
        if cache_key in self.query_cache:
            result, timestamp = self.query_cache[cache_key]
            if datetime.now() - timestamp < self.cache_ttl:
                # 更新缓存项的时间戳，实现LRU（最近最少使用）
                self.query_cache[cache_key] = (result, datetime.now())
                return result
            else:
                # 缓存过期，删除
                del self.query_cache[cache_key]
        
        # 语义搜索（使用原始查询文本进行更智能的匹配）
        if original_query:
            similar_key = self._find_similar_cache_key(original_query)
            if similar_key:
                result, timestamp = self.query_cache[similar_key]
                if datetime.now() - timestamp < self.cache_ttl:
                    self.cache_stats["semantic_matches"] += 1
                    # 更新缓存项的时间戳
                    self.query_cache[similar_key] = (result, datetime.now())
                    return result
        
        return None
    
    def _find_similar_cache_key(self, query_text: str, threshold: float = 0.8) -> Optional[str]:
        """
        查找语义相似的缓存键，改进为基于原始查询文本的语义相似度计算
        
        Args:
            query_text: 用户原始查询文本
            threshold: 相似度阈值
            
        Returns:
            最相似的缓存键，如果没有找到则返回None
        """
        try:
            if not self.query_cache:
                return None
            
            # 将查询文本转换为小写以进行不区分大小写的匹配
            query_text_lower = query_text.lower()
            query_words = set(query_text_lower.split())
            
            best_match = None
            best_similarity = 0.0
            
            for cache_key, (cached_result, _) in self.query_cache.items():
                # 尝试从缓存结果中获取原始查询文本
                cached_query = cached_result.get("original_query", "")
                
                if cached_query:
                    # 使用原始查询文本计算相似度
                    cached_query_lower = cached_query.lower()
                    cached_words = set(cached_query_lower.split())
                    
                    # 计算Jaccard相似度
                    intersection = len(query_words.intersection(cached_words))
                    union = len(query_words.union(cached_words))
                    
                    if union > 0:
                        similarity = intersection / union
                        
                        # 额外的关键词匹配检查
                        if any(keyword in query_text_lower and keyword in cached_query_lower for keyword in ["查询", "获取", "搜索", "查看", "分析"]):
                            similarity += 0.1  # 增加0.1的相似度
                        
                        # 检查服务类型匹配
                        if "selected_service" in cached_result:
                            service_name = cached_result["selected_service"]
                            if service_name in query_text_lower or service_name.replace("_", "") in query_text_lower:
                                similarity += 0.1  # 增加0.1的相似度
                        
                        similarity = min(similarity, 1.0)  # 确保相似度不超过1.0
                        
                        if similarity > best_similarity and similarity >= threshold:
                            best_similarity = similarity
                            best_match = cache_key
            
            # 记录语义匹配的情况
            if best_match:
                logger.debug(f"找到语义相似的缓存项，相似度: {best_similarity:.2f}")
            
            return best_match
        except Exception as e:
            logger.error(f"查找相似缓存键时出错: {str(e)}")
            return None
    
    def _add_to_cache(self, cache_key: str, result: Dict[str, Any], original_query: Optional[str] = None):
        """
        添加结果到缓存，保存原始查询文本以支持语义缓存
        
        Args:
            cache_key: 缓存键
            result: 要缓存的结果
            original_query: 原始查询文本
        """
        # 创建一个结果的深拷贝以避免外部修改影响缓存
        import copy
        cached_result = copy.deepcopy(result)
        
        # 保存原始查询文本以支持语义缓存
        if original_query:
            cached_result["original_query"] = original_query
        
        # 限制缓存大小，使用LRU（最近最少使用）策略
        if len(self.query_cache) >= 1000:
            # 删除最早添加的项
            oldest_key = min(self.query_cache.items(), key=lambda x: x[1][1])[0]
            del self.query_cache[oldest_key]
        
        self.query_cache[cache_key] = (cached_result, datetime.now())
        
        # 定期清理过期缓存，每50次添加操作执行一次
        if len(self.query_cache) % 50 == 0:
            self._cleanup_cache()
            
        # 记录缓存统计信息
        logger.debug(f"添加缓存项，当前缓存大小: {len(self.query_cache)}")
    
    def _cleanup_cache(self):
        """清理过期缓存"""
        current_time = datetime.now()
        expired_keys = [
            key for key, (_, timestamp) in self.query_cache.items()
            if current_time - timestamp > self.cache_ttl
        ]
        for key in expired_keys:
            del self.query_cache[key]
    
    def _fast_service_selection(self, user_query: str) -> Optional[Dict[str, Any]]:
        """快速服务选择（基于关键词和历史数据）"""
        # 使用服务注册表的find_relevant_services方法
        relevant_services = self.service_registry.find_relevant_services(user_query, top_n=1)
        
        if relevant_services:
            service_data = relevant_services[0]
            service_name = service_data['name']
            # 验证服务是否存在且处于活跃状态
            if self.service_registry.service_exists(service_name):
                service_status = self.service_registry.get_service_status(service_name)
                if service_status == ServiceStatus.ACTIVE:
                    confidence = service_data.get('match_score', 0.7)  # 使用匹配分数作为置信度
                    
                    # 尝试从查询中提取参数
                    parameters = self._extract_parameters_from_query(user_query, service_data)
                    
                    return {
                        "selected_service": service_name,
                        "confidence": confidence,
                        "parameters": parameters,
                        "reasoning": f"基于关键词匹配选择服务: {service_name}"
                    }
                else:
                    # 服务存在但不活跃
                    import logging
                    logging.warning(f"服务 {service_name} 存在但状态为 {service_status}，跳过快速匹配")
            else:
                # 服务不存在
                import logging
                logging.warning(f"快速匹配返回了不存在的服务: {service_name}")
        
        return None
    
    def _fallback_service_selection(self, user_query: str) -> Dict[str, Any]:
        """备选服务选择方案（基于关键词）"""
        # 打印当前已注册的服务，用于调试
        registered_services = self.service_registry.list_services()
        self.logger.info(f"备选服务选择开始，当前已注册的服务: {registered_services}")
        self.logger.info(f"处理用户查询: {user_query}")
        
        # 尝试快速匹配
        fast_result = self._fast_service_selection(user_query)
        self.logger.info(f"快速匹配结果: {fast_result}")
        if fast_result:
            selected_service = fast_result.get("selected_service", "")
            # 验证服务是否存在
            if self.service_registry.service_exists(selected_service):
                self.logger.info(f"快速匹配服务 '{selected_service}' 存在，直接返回")
                return fast_result
            else:
                # 如果快速匹配返回了不存在的服务，记录日志并继续处理
                self.logger.warning(f"快速匹配返回了不存在的服务: {selected_service}")
        
        # 特殊处理用户查询
        user_query_lower = user_query.lower()
        user_keywords = ["用户", "user", "账户", "account", "登录", "login", "admin", "userinfo", "用户信息", "查询用户", "获取用户"]
        self.logger.info(f"检查用户查询是否包含用户相关关键词: {user_keywords}")
        if any(keyword in user_query_lower for keyword in user_keywords):
            self.logger.info(f"用户查询包含用户相关关键词，正在处理用户管理服务选择")
            # 检查user_management服务是否存在
            if self.service_registry.service_exists("user_management"):
                self.logger.info(f"user_management服务存在，状态: {self.service_registry.get_service_status('user_management')}")
                # 尝试从查询中提取用户ID
                user_id = None
                
                # 更精确地匹配"查询用户xxx的信息"或"获取用户xxx的信息"模式
                user_info_match = re.search(r'(查询|获取)用户(\w+)的信息', user_query)
                if user_info_match:
                    user_id = user_info_match.group(2)
                    self.logger.info(f"从查询中提取到用户ID: {user_id}")
                else:
                    # 尝试匹配"用户:xxx"或"user:xxx"模式
                    user_match = re.search(r'(?:用户|user)[:：]?\s*(\w+)', user_query, re.IGNORECASE)
                    if user_match:
                        user_id = user_match.group(1)
                        self.logger.info(f"从查询中提取到用户ID: {user_id}")
                    else:
                        # 查找像"admin"这样的用户标识
                        for keyword in ["admin", "administrator", "root", "manager"]:
                            if keyword in user_query_lower:
                                user_id = keyword
                                self.logger.info(f"从查询中提取到用户ID: {user_id}")
                                break
                        # 如果还是没有找到用户ID，但查询明显是关于用户信息的，设置默认值
                        if not user_id and ("查询用户" in user_query_lower or "获取用户" in user_query_lower):
                            user_id = "admin"
                            self.logger.info(f"未明确指定用户ID，使用默认值: {user_id}")
                
                parameters = {}
                if user_id:
                    parameters["user_id"] = user_id
                    self.logger.info(f"设置用户管理服务参数: {parameters}")
                      
                result = {
                    "selected_service": "user_management",
                    "confidence": 0.9,
                    "parameters": parameters,
                    "reasoning": "检测到用户相关信息查询，默认使用用户管理服务"
                }
                self.logger.info(f"用户管理服务选择结果: {result}")
                return result
            else:
                # 如果user_management服务不存在，尝试动态注册它
                self.logger.warning(f"user_management服务不存在，将尝试注册它。已注册服务列表: {registered_services}")
                
                try:
                    from src.services.auth_service import get_user_info as auth_get_user_info
                    self.service_registry.register_service(
                        name="user_management",
                        service_func=auth_get_user_info,
                        description="用户认证和管理服务，包括用户信息查询、登录验证等功能",
                        parameters={"user_id": "用户ID或用户名", "username": "用户名"},
                        keywords=["用户", "登录", "认证", "管理", "信息"],
                        version="1.0.0"
                    )
                    self.logger.info("成功动态注册user_management服务")
                    
                    # 尝试从查询中提取用户ID
                    user_id = None
                    
                    # 更精确地匹配"查询用户xxx的信息"或"获取用户xxx的信息"模式
                    user_info_match = re.search(r'(查询|获取)用户(\w+)的信息', user_query)
                    if user_info_match:
                        user_id = user_info_match.group(2)
                        self.logger.info(f"从查询中提取到用户ID: {user_id}")
                    else:
                        # 尝试匹配"用户:xxx"或"user:xxx"模式
                        user_match = re.search(r'(?:用户|user)[:：]?\s*(\w+)', user_query, re.IGNORECASE)
                        if user_match:
                            user_id = user_match.group(1)
                            self.logger.info(f"从查询中提取到用户ID: {user_id}")
                        else:
                            # 查找像"admin"这样的用户标识
                            for keyword in ["admin", "administrator", "root", "manager"]:
                                if keyword in user_query_lower:
                                    user_id = keyword
                                    self.logger.info(f"从查询中提取到用户ID: {user_id}")
                                    break
                            # 如果还是没有找到用户ID，但查询明显是关于用户信息的，设置默认值
                            if not user_id and ("查询用户" in user_query_lower or "获取用户" in user_query_lower):
                                user_id = "admin"
                                self.logger.info(f"未明确指定用户ID，使用默认值: {user_id}")
                    
                    parameters = {}
                    if user_id:
                        parameters["user_id"] = user_id
                        self.logger.info(f"设置用户管理服务参数: {parameters}")
                      
                    result = {
                        "selected_service": "user_management",
                        "confidence": 0.9,
                        "parameters": parameters,
                        "reasoning": "检测到用户相关信息查询，已动态注册并使用用户管理服务"
                    }
                    self.logger.info(f"用户管理服务选择结果: {result}")
                    return result
                except Exception as e:
                    self.logger.error(f"动态注册user_management服务失败: {str(e)}")
                    self.logger.warning("将使用research_assistant服务")
        
        # 默认选择研究助理服务（确保选择一个已注册的服务）
        result = {
            "selected_service": "research_assistant",
            "confidence": 0.5,
            "parameters": {"question": user_query},
            "reasoning": "未找到匹配的服务，默认使用研究助理服务"
        }
        self.logger.warning(f"未找到匹配的特定服务，默认使用研究助理服务: {result}")
        return result
    
    def _extract_parameters_from_query(self, user_query: str, service_info: Dict[str, Any]) -> Dict[str, Any]:
        """
        从查询中智能提取参数，支持多种服务类型和参数格式
        
        Args:
            user_query: 用户查询文本
            service_info: 服务信息字典，包含描述、参数要求等
            
        Returns:
            提取出的参数字典
        """
        parameters = {}
        service_params = service_info.get('parameters', {})
        service_name = service_info.get('name', '').lower()
        user_query_lower = user_query.lower()
        
        # 通用参数提取模式
        # 1. 键值对模式: key:value 或 key=value
        key_value_patterns = [
            (r'(\w+)[:：]\s*(\S+)', 1, 2),  # key: value
            (r'(\w+)=([^\s,]+)', 1, 2),     # key=value
        ]
        
        for pattern, key_group, value_group in key_value_patterns:
            matches = re.findall(pattern, user_query)
            for match in matches:
                key = match[key_group-1].lower()
                value = match[value_group-1]
                # 如果键名在服务参数定义中，或者是常见参数名，则添加
                if key in service_params or key in ['id', 'name', 'query', 'question', 'title', 'description']:
                    parameters[key] = value
        
        # 2. 数值提取：如 "第3页"、"2023年"、"10个"等
        number_patterns = [
            (r'第?(\d+)页', 'page'),
            (r'(\d+)年', 'year'),
            (r'(\d+)月', 'month'),
            (r'(\d+)日', 'day'),
            (r'(\d+)个?', 'count'),
            (r'优先级([高|中|低])', 'priority'),
        ]
        
        for pattern, param_name in number_patterns:
            match = re.search(pattern, user_query)
            if match:
                parameters[param_name] = match.group(1)
        
        # 服务特定参数提取
        if "user" in service_name or "user_management" in service_name:
            # 用户相关服务
            self._extract_user_parameters(user_query, parameters)
        
        elif "research" in service_name:
            # 研究服务
            parameters.setdefault("question", user_query)
            # 提取研究范围、时间范围等参数
            if '从' in user_query and '到' in user_query:
                time_range_match = re.search(r'从(\d+[年|月|日])到(\d+[年|月|日])', user_query)
                if time_range_match:
                    parameters['start_time'] = time_range_match.group(1)
                    parameters['end_time'] = time_range_match.group(2)
            
        elif "ticket" in service_name:
            # 票务服务
            self._extract_ticket_parameters(user_query, parameters)
        
        elif "knowledge" in service_name:
            # 知识图谱服务
            parameters.setdefault("query", user_query)
            # 提取实体、关系等参数
            if '实体' in user_query_lower or 'entity' in user_query_lower:
                entity_match = re.search(r'(?:实体|entity):?\s*(\w+)', user_query, re.IGNORECASE)
                if entity_match:
                    parameters['entity'] = entity_match.group(1)
            elif '关系' in user_query_lower or 'relation' in user_query_lower:
                relation_match = re.search(r'(?:关系|relation):?\s*(\w+)', user_query, re.IGNORECASE)
                if relation_match:
                    parameters['relation'] = relation_match.group(1)
        
        elif "group" in service_name:
            # 组服务
            self._extract_group_parameters(user_query, parameters)
        
        # 为所有参数添加默认值（如果服务参数定义中有默认值）
        for param_name, param_info in service_params.items():
            if param_name not in parameters and isinstance(param_info, dict) and 'default' in param_info:
                parameters[param_name] = param_info['default']
        
        return parameters
    
    def _extract_user_parameters(self, user_query: str, parameters: Dict[str, Any]):
        """提取用户相关参数"""
        user_query_lower = user_query.lower()
        
        # 精确匹配"查询用户xxx的信息"模式
        user_info_match = re.search(r'查询用户(\w+)的信息', user_query)
        if user_info_match:
            parameters["user_id"] = user_info_match.group(1)
        else:
            # 尝试匹配"用户:xxx"或"user:xxx"模式
            user_match = re.search(r'(?:用户|user)[:：]?\s*(\w+)', user_query, re.IGNORECASE)
            if user_match:
                parameters["user_id"] = user_match.group(1)
            else:
                # 查找像"admin"这样的用户标识
                for keyword in ["admin", "administrator", "root", "manager", "user1", "user2"]:
                    if keyword in user_query_lower:
                        parameters["user_id"] = keyword
                        break
        
        # 提取操作类型
        if '创建' in user_query_lower:
            parameters['action'] = 'create'
        elif '删除' in user_query_lower:
            parameters['action'] = 'delete'
        elif '更新' in user_query_lower:
            parameters['action'] = 'update'
        elif '禁用' in user_query_lower:
            parameters['action'] = 'disable'
        elif '启用' in user_query_lower:
            parameters['action'] = 'enable'
        elif '重置' in user_query_lower and '密码' in user_query_lower:
            parameters['action'] = 'reset_password'
        elif '查询' in user_query_lower or '查看' in user_query_lower or '获取' in user_query_lower:
            parameters['action'] = 'query'
        
        # 提取用户属性参数
        if '属性' in user_query_lower or 'attributes' in user_query_lower:
            attr_match = re.search(r'(?:属性|attributes):?\s*(\w+)', user_query, re.IGNORECASE)
            if attr_match:
                parameters['attributes'] = attr_match.group(1)
        
        # 提取用户角色
        role_match = re.search(r'(?:角色|role)[:：]?\s*(\w+)', user_query, re.IGNORECASE)
        if role_match:
            parameters['role'] = role_match.group(1)
        
        # 提取部门信息
        department_match = re.search(r'(?:部门|department)[:：]?\s*(\w+)', user_query, re.IGNORECASE)
        if department_match:
            parameters['department'] = department_match.group(1)
        
        # 提取状态信息
        if '在线' in user_query_lower or 'active' in user_query_lower:
            parameters['status'] = 'active'
        elif '离线' in user_query_lower or 'inactive' in user_query_lower:
            parameters['status'] = 'inactive'
        elif '锁定' in user_query_lower or 'locked' in user_query_lower:
            parameters['status'] = 'locked'
    
    def _extract_ticket_parameters(self, user_query: str, parameters: Dict[str, Any]):
        """提取票务相关参数"""
        user_query_lower = user_query.lower()
        
        # 尝试提取标题
        title_end = user_query.find('。') if '。' in user_query else min(50, len(user_query))
        parameters.setdefault("title", user_query[:title_end].strip())
        
        # 提取描述
        parameters.setdefault("description", user_query)
        
        # 提取优先级
        if '优先级' in user_query:
            priority_match = re.search(r'优先级([高|中|低])', user_query)
            if priority_match:
                priority_map = {'高': 'high', '中': 'medium', '低': 'low'}
                parameters['priority'] = priority_map.get(priority_match.group(1), 'normal')
        else:
            parameters.setdefault("priority", "normal")
        
        # 提取工单类型
        if '故障' in user_query_lower:
            parameters['type'] = 'incident'
        elif '需求' in user_query_lower:
            parameters['type'] = 'requirement'
        elif '问题' in user_query_lower:
            parameters['type'] = 'problem'
        elif '任务' in user_query_lower:
            parameters['type'] = 'task'
        elif '请求' in user_query_lower:
            parameters['type'] = 'request'
        elif '建议' in user_query_lower:
            parameters['type'] = 'suggestion'
        
        # 提取工单ID
        ticket_id_match = re.search(r'(?:工单|ticket)[:：]?\s*(\d+)', user_query, re.IGNORECASE)
        if ticket_id_match:
            parameters['ticket_id'] = ticket_id_match.group(1)
        
        # 提取操作类型
        if '创建' in user_query_lower:
            parameters['action'] = 'create'
        elif '删除' in user_query_lower:
            parameters['action'] = 'delete'
        elif '更新' in user_query_lower:
            parameters['action'] = 'update'
        elif '关闭' in user_query_lower:
            parameters['action'] = 'close'
        elif '分配' in user_query_lower:
            parameters['action'] = 'assign'
        elif '处理' in user_query_lower:
            parameters['action'] = 'process'
        elif '查询' in user_query_lower or '查看' in user_query_lower or '获取' in user_query_lower:
            parameters['action'] = 'query'
        
        # 提取分配用户
        assign_match = re.search(r'(?:分配给|assign to)[:：]?\s*(\w+)', user_query, re.IGNORECASE)
        if assign_match:
            parameters['assigned_to'] = assign_match.group(1)
        
        # 提取截止日期
        deadline_match = re.search(r'(?:截止日期|deadline)[:：]?\s*(\d{4}-\d{2}-\d{2})', user_query, re.IGNORECASE)
        if deadline_match:
            parameters['deadline'] = deadline_match.group(1)
    
    def _extract_group_parameters(self, user_query: str, parameters: Dict[str, Any]):
        """提取群组相关参数"""
        user_query_lower = user_query.lower()
        
        # 精确匹配"查询组xxx的信息"或"获取组xxx的成员"等模式
        group_info_match = re.search(r'(?:查询|获取|查看)(?:组|群组)(\w+)(?:的信息|的成员|的详情)', user_query)
        if group_info_match:
            parameters["group_id"] = group_info_match.group(1)
        else:
            group_match = re.search(r'(?:组|group)[:：]?\s*(\w+)', user_query, re.IGNORECASE)
            if group_match:
                parameters["group_id"] = group_match.group(1)
            else:
                # 查找像"team1"或"group1"这样的群组标识
                for keyword in ["team1", "team2", "group1", "group2", "开发组", "测试组"]:
                    if keyword.lower() in user_query_lower:
                        parameters["group_id"] = keyword
                        break
        
        # 提取操作类型
        if '创建' in user_query_lower:
            parameters['action'] = 'create'
        elif '删除' in user_query_lower:
            parameters['action'] = 'delete'
        elif '更新' in user_query_lower:
            parameters['action'] = 'update'
        elif '成员' in user_query_lower:
            parameters['action'] = 'list_members'
        elif '加入' in user_query_lower:
            parameters['action'] = 'join'
        elif '退出' in user_query_lower:
            parameters['action'] = 'leave'
    
    def get_service_descriptions(self) -> Dict[str, str]:
        """获取所有服务的描述信息"""
        services = self.service_registry.get_all_services()
        return {
            name: info['description'] 
            for name, info in services.items()
        }

    def _normalize_service_name(self, service_name: str) -> str:
        """标准化服务名称，转换为小写并去除空格"""
        return service_name.lower().strip()

    def _is_service_available(self, service_name: str) -> bool:
        """检查服务是否可用"""
        services = self.service_registry.get_all_services()
        normalized_name = self._normalize_service_name(service_name)
        
        for name in services.keys():
            if self._normalize_service_name(name) == normalized_name:
                # 检查服务的可用性状态
                if services[name].get('available', True):
                    return True
                return False
        
        return False
        
    def _validate_parameters(self, service_name: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """验证并清理服务参数"""
        services = self.service_registry.get_all_services()
        service_params = services.get(service_name, {}).get('parameters', {})
        validated_params = {}
        
        # 对每个参数进行验证和类型转换
        for param_name, param_value in parameters.items():
            if param_name in service_params:
                param_info = service_params[param_name]
                # 进行类型转换
                try:
                    if isinstance(param_info, dict) and 'type' in param_info:
                        param_type = param_info['type']
                        if param_type == 'int' and not isinstance(param_value, int):
                            validated_params[param_name] = int(param_value)
                        elif param_type == 'float' and not isinstance(param_value, float):
                            validated_params[param_name] = float(param_value)
                        elif param_type == 'bool' and not isinstance(param_value, bool):
                            # 处理字符串形式的布尔值
                            if isinstance(param_value, str):
                                validated_params[param_name] = param_value.lower() in ['true', 'yes', '1']
                            else:
                                validated_params[param_name] = bool(param_value)
                        elif param_type == 'list' and not isinstance(param_value, list):
                            # 将逗号分隔的字符串转换为列表
                            if isinstance(param_value, str):
                                validated_params[param_name] = [item.strip() for item in param_value.split(',')]
                            else:
                                validated_params[param_name] = [param_value]
                        else:
                            # 类型匹配或不需要转换
                            validated_params[param_name] = param_value
                    else:
                        # 没有参数定义或定义不完整，直接使用原始值
                        validated_params[param_name] = param_value
                except (ValueError, TypeError):
                    # 类型转换失败，记录警告但保留原始值
                    self.logger.warning(f"Failed to convert parameter '{param_name}' to expected type for service '{service_name}'")
                    validated_params[param_name] = param_value
            else:
                # 未知参数，直接保留
                validated_params[param_name] = param_value
                
        return validated_params
        
    def _get_default_parameters(self, service_name: str) -> Dict[str, Any]:
        """获取服务的默认参数"""
        services = self.service_registry.get_all_services()
        service_params = services.get(service_name, {}).get('parameters', {})
        default_params = {}
        
        for param_name, param_info in service_params.items():
            if isinstance(param_info, dict) and 'default' in param_info:
                default_params[param_name] = param_info['default']
                
        return default_params
        
    def _get_service_dependencies(self, service_name: str) -> List[str]:
        """获取服务的依赖关系"""
        services = self.service_registry.get_all_services()
        return services.get(service_name, {}).get('dependencies', [])
        
    def _check_service_dependencies(self, service_name: str) -> Dict[str, Any]:
        """检查服务的所有依赖是否可用"""
        dependencies = self._get_service_dependencies(service_name)
        missing_dependencies = []
        
        for dependency in dependencies:
            if not self._is_service_available(dependency):
                self.logger.warning(f"Service '{service_name}' dependency '{dependency}' is not available")
                missing_dependencies.append(dependency)
                
        return {
            "all_available": len(missing_dependencies) == 0,
            "missing_dependencies": missing_dependencies
        }
    
    def list_available_services(self) -> List[Dict[str, Any]]:
        """列出所有可用服务的详细信息"""
        services = self.service_registry.get_all_services()
        result = []
        
        for name, info in services.items():
            result.append({
                "name": name,
                "description": info['description'],
                "parameters": info.get('parameters', {}),
                "keywords": info.get('keywords', []),
                "examples": info.get('examples', []),
                "version": info.get('version', '1.0.0')
            })
        
        return result
    
    def get_cache_stats(self) -> Dict[str, Any]:
        """获取缓存统计信息"""
        total = self.cache_stats["hits"] + self.cache_stats["misses"]
        hit_rate = self.cache_stats["hits"] / total if total > 0 else 0
        semantic_rate = self.cache_stats["semantic_matches"] / self.cache_stats["hits"] if self.cache_stats["hits"] > 0 else 0
        
        return {
            "hits": self.cache_stats["hits"],
            "misses": self.cache_stats["misses"],
            "semantic_matches": self.cache_stats["semantic_matches"],
            "total": total,
            "hit_rate": int(hit_rate * 100),  # 转换为百分比整数
            "semantic_match_rate": int(semantic_rate * 100),  # 转换为百分比整数
            "cached_items": len(self.query_cache)
        }


# 全局服务协调器实例
service_orchestrator = ServiceOrchestrator()


def get_service_orchestrator() -> ServiceOrchestrator:
    """获取服务协调器实例"""
    return service_orchestrator


# 导出
__all__ = ["ServiceOrchestrator", "service_orchestrator", "get_service_orchestrator"]